#include "Surface.h"
#include "texture.h"
#include "base.h"
#include "Renderer.h"
#include "Constant.h"

Surface::Surface()
{
	m_pSurface = NULL;
	m_bValidSurface = false;
}
Surface::Surface(SDL_Surface *surf)
{
	if(surf == NULL)
	{
		m_pSurface = NULL;
		m_bValidSurface = false;
		return;
	}

	m_pSurface = surf;
	m_bValidSurface = true;
}
Surface::~Surface()
{
	FreeSurface();
}
SDL_Surface *Surface::GetSurface()
{
	return m_pSurface;
}
void Surface::FreeSurface()
{
	if(IsValidSurface())
	{
		SDL_FreeSurface(m_pSurface);
		m_pSurface = NULL;
		m_bValidSurface = false;
	}
}
bool Surface::IsValidSurface()
{
	if(!m_bValidSurface)
		return false;
	if(m_pSurface == NULL)
	{
		m_bValidSurface = false;
		return false;
	}
	return true;
}
Texture Surface::CreateTexture()
{
	return Texture(this);
}
void Surface::OptimizeSelf()
{
	SDL_Surface *sNew = SDL_CreateRGBSurface(m_pSurface->flags, m_pSurface->w, m_pSurface->h,
		m_pSurface->format->BitsPerPixel, m_pSurface->format->Rmask, m_pSurface->format->Gmask, m_pSurface->format->Bmask, m_pSurface->format->Amask);
	SDL_BlitSurface(m_pSurface, NULL, sNew, NULL);
	SDL_FreeSurface(m_pSurface);

	//Assign new surface
	m_pSurface = sNew;
	m_bValidSurface = true;
}
Surface Surface::Optimize()
{
	SDL_Surface *sNew = SDL_CreateRGBSurface(m_pSurface->flags, m_pSurface->w, m_pSurface->h,
		m_pSurface->format->BitsPerPixel, m_pSurface->format->Rmask, m_pSurface->format->Gmask, m_pSurface->format->Bmask, m_pSurface->format->Amask);
	SDL_BlitSurface(m_pSurface, NULL, sNew, NULL);
	return Surface(sNew);
}
Surface Surface::Copy()
{
	if(!IsValidSurface())
	{
		return Surface();
	}

	SDL_Surface *sNew = SDL_CreateRGBSurface(NULL, m_pSurface->w, m_pSurface->h,
			SCREEN_BPP, 0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000);
	SDL_BlitSurface(m_pSurface, NULL, sNew, NULL);

	return Surface(sNew);
}
uint Surface::Depth()
{
	return m_pSurface->format->BitsPerPixel;
}
uint Surface::Width()
{
	return m_pSurface->w;
}
uint Surface::Heigth()
{
	return m_pSurface->h;
}